<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 

class Layout {
	
	protected $_tpls = array();
	
	public function __construct() {
		App::library('template');
		foreach (App::config('templates') as $tpl) {
			$this->addTemplate($tpl);
		}
	}
	
	protected function getLayoutFile($controller) {
		$result = null;
		foreach ($this->_tpls as $tpl) {
			$result = APPDIR.$tpl->getLayout($controller);
			if (file_exists($result)) break;
		}
		return $result;
	}
	
	public function getTemplate($path) {
		$result = null;
		foreach ($this->_tpls as $tpl) {
			$result = $tpl->getTemplate($path);
			if (file_exists(APPDIR.'views/'.$result.'php')) break;
		}
		return $result;
	}
	
	public function getSkinUrl($item) {
		$result = null;
		foreach ($this->_tpls as $tpl) {
			$result = $tpl->getSkin($item);
			if (file_exists(APPDIR.'skin/'.$result)) break;
		}
		return base_url('application/skin/' . $result);
	}
	
	public function addTemplate($name) {
		array_unshift($this->_tpls, new Template($name));
		return $this;
	}
	
	public function loadLayout($controller, $action) {
		// get layout xml file
		$layout = $this->getLayoutFile($controller);
		
		// load default tag
		$xml = simplexml_load_file($layout);
		$default = $this->blockFromXml($xml->default->page);
		
		// load controller action tag
		$tagName = $controller.'_'.$action;
		$childs = $xml->{$tagName}->children();	// page tag
		return $this->blockFromXml($childs)->attach($default);
	}
	
	protected function blockFromXml($xml) {
		$type = ($xml->attributes()->block ? $xml->attributes()->block : 'decorator');
		$result = $this->createBlock($type);
		if ($xml->attributes()->template) $result->setTemplate($xml->attributes()->template);
		
		foreach ($xml->children() as $child) {
			$subBlock = $this->blockFromXml($child);
			$result->setChild($child->getName(), $subBlock);
		}
		return $result;
	}
	
	public function createBlock($type) {
		$path = 'block/'. capitalize($type);
		$class = str_replace('/','_',capitalize('block/'.$type));
		require_once(APPDIR.$path . '.php');
		$result = new $class();
		return $result;
	}
	
}

/* End of file Layout.php */